//
//  PlaceholderTextView.m
//  Budejie
//
//  Created by 远成物流 on 2017/6/7.
//  Copyright © 2017年 陈梦佳. All rights reserved.
//

#import "PlaceholderTextView.h"
#import <SDAutoLayout/SDAutoLayout.h>

@interface PlaceholderTextView ()

@property(nonatomic,strong)UILabel *placeholderLabel;

@end

@implementation PlaceholderTextView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        UILabel *label = Alloc(UILabel);
        label.left_sd = 5;
        label.top_sd = 5;
        label.textColor = [UIColor lightGrayColor];
        label.font = self.font;
        label.numberOfLines = 0;
        [self addSubview:label];
        
        self.placeholderLabel = label;
        
        //监听文字改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:self];
    }
    
    return self;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)textChange{
    if (self.placeholder.length) {
        self.placeholderLabel.hidden = YES;
    }else{
        self.placeholderLabel.hidden = NO;
    }
}

-(void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    
    self.placeholderLabel.text = placeholder;
    CGSize labelMaxSize = CGSizeMake(self.width_sd, MAXFLOAT);
    CGSize labelSize = [placeholder boundingRectWithSize:labelMaxSize options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.placeholderLabel.font} context:nil].size;
    self.placeholderLabel.size = labelSize;
}

-(void)setPlaceholderColor:(UIColor *)placeholderColor{
    _placeholderColor = placeholderColor;
    
    self.placeholderLabel.textColor = placeholderColor;
}

-(void)setFont:(UIFont *)font{
    [super setFont:font];
    
    self.placeholderLabel.font = font;
}

@end
